﻿namespace LeetCodeProject._0001_1000._001_100._21_30._029;

public class Solution
{
    public int Divide(int dividend, int divisor)
    {
        if (divisor == 0) throw new DivideByZeroException();
        if (dividend == 0)
            return 0;
        var sign = 1;
        if (dividend > 0)
        {
            sign = -sign;
            dividend = -dividend;
        }

        if (divisor > 0)
        {
            sign = -sign;
            divisor = -divisor;
        }

        var result = 0;
        var n = -1;

        while (divisor >= (int.MinValue >> 1))
        {
            divisor <<= 1;
            n <<= 1;
        }

        while (true)
        {
            if (dividend <= divisor)
            {
                result += n;
                dividend -= divisor;
            }

            if (n == -1) break;
            divisor >>= 1;
            n >>= 1;
        }

        if (sign == 1)
        {
            return result == int.MinValue ? int.MaxValue : -result;
        }

        return result;
    }
}